﻿using System;
using System.Windows.Browser;
using EarthWatchers.SL.Layers;
using EarthWatchers.SL.Requests;
using System.Collections.Generic;
using System.Windows;
using Earthwatchers.Models;
using EarthWatchers.SL.TIG;
using System.Windows.Input;
namespace EarthWatchers.SL.GUI.Controls
{
    //TODO: @time Refactor setting of loading/nouser/loggedin

	public partial class UserInfo
	{
        private readonly EarthwatcherRequests earthwatcherRequest = new EarthwatcherRequests(Constants.BaseApiUrl);
        private readonly LandRequests landRequest = new LandRequests(Constants.BaseApiUrl);
        private readonly TigParser tigParser = new TigParser();
        private readonly AuthenticationRequest authenticationRequest =new AuthenticationRequest();
        public delegate void ChangedEventHandler(object sender, EventArgs e);
        public event ChangedEventHandler UserLoggedIn;
        public event ChangedEventHandler UserLoggedOut;

        private Earthwatcher earthwatcher;
	    private Zone zone;
	    
        public UserInfo()
		{
			InitializeComponent();
            authenticationRequest.AuthenticateReceived += AuthenticationChanged;
		}

        private void EarthwatcherChanged(object sender, EventArgs e)
        {
            GridLoading.Visibility = Visibility.Collapsed;

            earthwatcher = sender as Earthwatcher;
            Current.Instance.Earthwatcher = earthwatcher;

            if (earthwatcher == null)
            {
                txtIncorrectLogin.Visibility = Visibility.Visible;
                GridNoUser.Visibility = Visibility.Visible;           
                return;
            }

            GridNoUser.Visibility = Visibility.Collapsed;  
            GridLogedIn.Visibility = Visibility.Visible;

            label.Content = earthwatcher.Name;

            var flagLayer = Current.Instance.LayerHelper.FindLayer(Constants.flagLayerName) as FlagLayer;
            if (flagLayer != null) flagLayer.RequestFlags();

            //RequestFromUsername requesting the land for the user
            landRequest.LandReceived += LandChanged;
            landRequest.GetLandById(earthwatcher.LandId.ToString());

            UserLoggedIn(this, EventArgs.Empty);
        }

        private void TigParserTigUserReceived(object sender, EventArgs e)
        {
            var tigUserInfo = sender as TigUserinfo;

            if (tigUserInfo == null || !Current.Instance.IsAuthenticated) 
                return;

            Current.Instance.TigUserInfo = tigUserInfo;
            avatar.Source = tigUserInfo.AvatarSmall;
        }

        //Received land of the user, parse the info and show it to the user
        private void AuthenticationChanged(object sender, EventArgs e)
        {
            Current.Instance.IsAuthenticated = (bool)sender;
            if (!Current.Instance.IsAuthenticated)//if authkey is incorrect do not load userinfo
            {
                txtIncorrectLogin.Visibility = Visibility.Visible;
                SetGuiForNoUser();
                return;
            }

            earthwatcherRequest.EarthwatcherReceived += EarthwatcherChanged;
            earthwatcherRequest.GetByName(Current.Instance.Username);

            tigParser.GetUserInfo(Current.Instance.Username);
            tigParser.TigUserReceived += TigParserTigUserReceived;
        }

	    //Received land of the user, parse the info and show it to the user
        private void LandChanged(object sender, EventArgs e)
        {
            var land = sender as Land;
            
            if(land == null) 
                return;

            Current.Instance.EarthwatcherLand = land;
            zone = GeoHex.Decode(land.GeohexKey);
                        
            var hexagonLayer = Current.Instance.LayerHelper.FindLayer(Constants.Hexagonlayername) as HexagonLayer;
            
            if (hexagonLayer != null && zone != null) 
                hexagonLayer.AddHexagon(zone, LandStatus.NotChecked, true);

            MapHelper.ZoomToHexagon(Current.Instance.MapControl, land.GeohexKey);
        }

        public void TryGetUserInfo()
        {          
            try
            {
                //this is obtained via the current url
                var username = HtmlPage.Document.QueryString["username"];

                try
                {
                    var authkey = HtmlPage.Document.QueryString["pwchunk"];
                    GetUserInfo(username, authkey);
                }
                catch (KeyNotFoundException)//no username provided, return
                {
                    SetGuiForNoUser();
                }
            }
            catch (KeyNotFoundException)//no username provided, return
            {
                SetGuiForNoUser();
            }
        }

        public void GetUserInfo(string username, string authkey)
        {
            GridNoUser.Visibility = Visibility.Collapsed;
            GridLogedIn.Visibility = Visibility.Collapsed;
            GridLoading.Visibility = Visibility.Visible;
            Current.Instance.Username = username;
            Current.Instance.Password= authkey;
            authenticationRequest.Authenticate(Constants.BaseApiUrl,username, authkey);
        }
        
        private void SetGuiForNoUser()
        {
            GridLoading.Visibility = Visibility.Collapsed;
            GridNoUser.Visibility = Visibility.Visible;            
        }


        private void BtnMyLandClick(object sender, RoutedEventArgs e)
        {
            MapHelper.ZoomToHexagon(Current.Instance.MapControl, Current.Instance.EarthwatcherLand.GeohexKey);
        }

        private void BtnLoginClick(object sender, RoutedEventArgs e)
        {
            GetUserInfo(tbUsername.Text, tbAuthkey.Password);
        }

        private void TbUsernameGotFocus(object sender, RoutedEventArgs e)
        {
            tbUsername.SelectAll();
        }

        private void TbAuthkeyGotFocus(object sender, RoutedEventArgs e)
        {
            tbAuthkey.SelectAll();
        }


        private void BtnHelpMouseLeftButtonDown2(object sender, MouseButtonEventArgs e)
        {
            var helpWindow = new HelpWindow();
            helpWindow.Show();
        }


        private void TxtLogoutClick(object sender, RoutedEventArgs e)
        {
            var hexagonLayer = Current.Instance.LayerHelper.FindLayer(Constants.Hexagonlayername) as HexagonLayer;
            var land = Current.Instance.EarthwatcherLand;

            if (hexagonLayer != null && land != null)
                hexagonLayer.ChangeHexagon(land.GeohexKey, land.LandStatus);

            Current.Instance.EarthwatcherLand = null;
            Current.Instance.Earthwatcher = null;
            Current.Instance.TigUserInfo = null;
            Current.Instance.IsAuthenticated = false;

            txtIncorrectLogin.Visibility = Visibility.Collapsed;
            GridLoading.Visibility = Visibility.Collapsed;
            GridLogedIn.Visibility = Visibility.Collapsed;
            GridNoUser.Visibility = Visibility.Visible;

            Current.Instance.MapControl.OnViewChanged(true);

            UserLoggedOut(this, EventArgs.Empty);
        }
    }
}